<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/1/26
 * Time: 17:26
 * Desc: 会员中心
 */
namespace app\index\service;
use think\Controller;
use think\Db;
use app\index\service\WeixinService;
//use Qiniu;
//use Qiniu\Auth;
//use Qiniu\Storage\UploadManager;
use app\comm\service\DadaOpenapi;
use gmars\qiniu\Qiniu;
//use think\Paginator;

class UserService extends Controller{
    /**
     * @Author  lingyun
     * @Desc    获取头部信息
     */
    public function get_header(){
        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 6> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 AND a.status=1 AND a.is_deleted=0 AND is_top>0 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类
        $this->assign('tui_goods',$tui_goods);
        $this->assign('category',$category);
        $this->assign('exp_category',$exp_category);

    }

    /**
     * @Author  lingyun
     * @Desc    获取会员信息
     */
    public function get_user_info(){
        $uid = session('_user_uid_.uid');
        $user = Db::name('user')->where('uid',$uid)->find();        //会员信息
        $store = db('store')->where('id',cookie('store_id'))->find();
//        $level_info = get_user_level($user['level_point']);         //会员的等级信息
        $level_info = get_user_level($user['level_id']);         //会员的等级信息
        $user['mobile'] = substr_replace($user['mobile'],'****',3,4);

        $this->assign('user',$user);                    //会员信息
        $this->assign('store',$store);                    //会员信息
        $this->assign('level_info',$level_info);        //会员等级信息
    }

    /**
     * @Author  lingyun
     * @Desc    个人中心 -- 订单导航栏信息
     *          个人订单的支付形式
     */
    public function index_order_nav(){
        $store_id = session('store_id');
        $uid = session('_user_uid_.uid');
        $unpay_order = db('order')->where(['order_status'=>0,'store_id'=>$store_id,'uid'=>$uid])->count();       //未支付订单
        $undelivery_order = db('order')->where(['order_status'=>1,'store_id'=>$store_id,'uid'=>$uid])->count();  //未发货订单
        $delivery_order = db('order')->where(['order_status'=>3,'store_id'=>$store_id,'uid'=>$uid])->count();       //未已发货订单
        $complete_order = db('order')->where(['order_status'=>4,'store_id'=>$store_id,'uid'=>$uid])->count();       //未支付订单
        $order = [
            'unpay_order'=>$unpay_order,
            'undelivery_order'=>$undelivery_order,
            'delivery_order'=>$delivery_order,
            'complete_order'=>$complete_order
        ];
        $this->assign('order',$order);
    }

    /**
     * @Author  lingyun
     * @Desc    会员中心首页 -- 查询可用优惠券的数量
     */
    public function user_index_coupon_nav(){
        $uid = session('_user_uid_.uid');       //会员id
        $store_id = cookie('store_id');        //门店id
        //普通优惠券
        $where_pt_coupon = [
            'uid'=>$uid,
            'store_id'=>$store_id,
            'is_used'=>0,
            'type'=>['neq',3],
            'use_end_time'=>['gt',time()]
        ];
        //普通优惠券的可用数量
        $pt_coupon = db('user_ycard')->where($where_pt_coupon)->count();

//        $where_attention = [
//            'uid'=>$uid,
//            'store_id'=>$store_id,
//            'is_used'=>0,
//        ];
//        $at_coupon = db('user_ycard')->where($where_attention)->count();
        $this->assign('coupon_num',$pt_coupon);      //可用的优惠券数量
    }

    /**
     * @Author  lingyun
     * @Desc    我的订单
     *          订单列表的订单信息只展示两个商品信息
     *          订单状态,0待支付，1待发货，2已确认，3商家已发货，4已收货，5申请退货，6退货完成，8订单已取消（超过30分钟未支付就置为取消状态）
     *          订单未支付0：取消订单 -- 去支付
     *          订单已支付待发货1：取消订单
     *          订单已发货3：确认收货（订单已完成）
     *          订单已收货4：去评价 -- 订单已完成
     * @return mixed
     */
    public function my_order(){
        $uid = session('_user_uid_.uid');
        $status = input('status');
        $store_id = cookie('store_id');        //门店id

        $where_order = " where a.uid=".$uid." and a.store_id=".$store_id;
        $map['a.uid'] = ['eq',$uid];
        $map['a.store_id'] = ['eq',$store_id];
        $map['a.order_type'] = ['eq',1];
        if($status == 2){       //已发货的订单
            $where_order .= " and a.order_status>1 and a.order_status<4";
            $map['a.order_status'] = array(array('gt',1),array('lt',4),'AND');
        }else if($status !== null){
            $where_order .= " and a.order_status=".$status;
            $map['a.order_status'] = ['eq',$status];
        }

        $map1['order_status'] = array(array('gt',1),array('lt',4),'AND');
        $shouhuo_order = db('order')->where($map1)->count();
        //订单管理
//        $sql = "select a.id,a.uid,a.final_amount,a.order_sn,a.order_status,a.pay_time,a.addtime from ys_order as a".$where_order;
//        $list_arr = Db::query($sql);        //订单信息

        $list_arr = db('order')->alias('a')->where($map)->order('id desc')->field('a.id,a.uid,a.final_amount,a.order_sn,a.order_status,a.pay_time,a.addtime,goods_num,a.is_comment')->paginate(10,false,['query'=>request()->param()]);
        $page = $list_arr->render();
        //订单详情
        $sql_detail = "SELECT a.order_id,a.spec_detail,a.goods_id,a.goods_num,a.spec_price,b.name,b.logo FROM ys_goods as b left join (select * from ys_order_details AS c WHERE 2 > (SELECT COUNT(*) FROM ys_order_details  WHERE order_id=c.order_id AND id>c.id)) as a on a.goods_id=b.id ";


        $list_detail = Db::query($sql_detail);      //订单详情
        $this->assign('list',$list_arr);
        $this->assign('all_count_list',$list_arr->all());
        $this->assign('shouhuo_order',$shouhuo_order);
        $this->assign('list_detail',$list_detail);
        $this->assign('status',$status);
        $this->assign('page',$page);
    }

    /**
     * @Author  lingyun
     * @Desc    订单详情
     */
    public function order_detail(){
        $id = input('id');
        $where_order['id'] = ['eq',$id];
        $where_order_detail['order_id'] = ['eq',$id];
        $order = db('order')->where($where_order)->find();
        $order['coupon_amount'] = $order['coupon_price']+$order['cash_coupon_price'];
        $order_detail = db('view_myorder_detail')->where($where_order_detail)->select();
//        $order_detail = db('view_myorder_detail')->where('id',$id)->select();
//        $order = db('order')->where('id',$order_detail[0]['order_id'])->find();
        $order_action = db('order_action')->where('order_id',$id)->order('id asc')->select();
        $store = db('store')->where('id',$order['store_id'])->find();

        $this->assign('store_info',$store);
        $this->assign('order',$order);
        $this->assign('order_detail',$order_detail);
        $this->assign('order_action',$order_action);
    }

    /**
     * @Author  lingyun
     * @Desc    评价商品详情
     */
    public function pingjia_order_detail(){
        $id = input('id');

        $where_order['id'] = ['eq',$id];
        $where_order_detail['order_id'] = ['eq',$id];
//        $order_detail = db('view_myorder_detail')->where($where_order_detail)->select();
        $order_detail = db('view_myorder_detail')->where('order_id',$id)->select();
        $order = db('order')->where('id',$order_detail[0]['order_id'])->find();
        $order['coupon_amount'] = $order['coupon_price']+$order['cash_coupon_price'];
        $order_action = db('order_action')->where('order_id',$id)->order('id asc')->select();

        $store = db('store')->where('id',$order['store_id'])->find();
        $this->assign('store_info',$store);
        $this->assign('order',$order);
        $this->assign('order_detail',$order_detail);
        $this->assign('order_action',$order_action);
    }

    /**
     * @Author  lingyun
     * @Desc    评价商品详情
     * 2018-06-19
     */
    public function pingjia_goods_details(){
        $id = input('id');

        $where_order['id'] = ['eq',$id];
        $where_order_detail['id'] = ['eq',$id];
//        $order_detail = db('view_myorder_detail')->where($where_order_detail)->select();
        $order_detail = db('view_myorder_detail')->where('id',$id)->select();
        $order = db('order')->where('id',$order_detail[0]['order_id'])->find();
        $order['coupon_amount'] = $order['coupon_price']+$order['cash_coupon_price'];
        $order_action = db('order_action')->where('order_id',$id)->order('id asc')->select();

        $store = db('store')->where('id',$order['store_id'])->find();
        $this->assign('store_info',$store);
        $this->assign('order',$order);
        $this->assign('order_detail',$order_detail);
        $this->assign('order_action',$order_action);
    }

    /**
     * @Author  lingyun
     * @Desc    查询订单详情
     */
    private function delivery_order_action($order_id){
        $config_arr = config('dada');
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/accept";                //模拟接受订单
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/fetch";                 //模拟完成取货
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/finish";                //模拟完成订单
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/cancel";                //模拟取消订单
//        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/expire";                //模拟订单过期
        $config_arr['url'] = "http://newopen.qa.imdada.cn/api/order/status/query";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['order_id'] = '20180206195244991005350013';
        $result = $dada_obj->makeRequest($data_arr);
        if(!$result){
            echo $dada_obj->getCode();
            echo $dada_obj->getStatus();
            echo $dada_obj->getMsg();
            halt($dada_obj->getResult());
        }
    }

    /**
     * @Author  lingyun
     * @Desc    删除订单 -- 删除未支付的订单
     */
    public function del_order(){
        $post = input('param.');
        db('order')->where('id',$post['id'])->delete();     //删除订单
        db('order_details')->where('order_id',$post['id'])->delete();
        db('order_action')->where('order_id',$post['id'])->delete();

        $this->success('删除成功',url('User/index'));
    }


        /**
     * @Author  lingyun
     * @Desc    取消订单
     */
    public function cancel_order(){
        $post = input('param.');
        $order = db('order')->where('id',$post['id'])->field('id,order_sn,final_amount,pay_status,order_status,uid,store_id,pay_type')->find();

        if($order['order_status'] > 1){     //订单已发货
            $this->error('该订单已发货，不能取消订单,如有疑问联系商家',url('User/index'));
        }
        db('order')->where('id',$post['id'])->update(['order_status'=>8]);     //取消订单
        db('order_details')->where('order_id',$post['id'])->update(['status'=>8]);


        $order_action_arr = [
            'uid'=>$order['uid'],
            'order_id'=>$order['id'],
            'action_user'=>0,
            'order_status'=>8,
            'pay_status'=>$order['pay_status'],
            'status_desc'=>'订单已取消',
            'storeid'=>$order['store_id'],
            'addtime'=>time()
        ];
        //记录订单状态信息
        db('order_action')->insert($order_action_arr);


        //会员余额退款 -- 仅支付的订单才退款
        if($order['pay_status'] == 1){
            db('user')->where('uid',$order['uid'])->setInc('user_money',$order['final_amount']);
            $user = db('user')->where('uid',$order['uid'])->field('uid,user_money,nickname')->find();
            $refund_log = [
                'uid'=>$order['uid'],
                'store_id'=>$order['store_id'],
                'order_id'=>$order['id'],
                'order_sn'=>$order['order_sn'],
                'pay_type'=>$order['pay_type'],
                'pay_status'=>1,
                'amount'=>$order['final_amount'],
                'cur_amount'=>$user['user_money'],
                'sign'=>2,
                'chargetype'=>2,
                'charge_cn'=>'取消订单，退还金额',
                'addtime'=>time()
            ];
            db('user_wallet_log')->data($refund_log)->insert();  //记录退款日志
        }

        $this->success('取消成功',url('User/index'));
    }


    /**
     * @Author  lingyun
     * @Desc    确认收货
     *          赠送积分 -- 将优惠券置为可用状态 -- 更新会员等级 -- 更新会员当前积分
     *          更新订单状态 -- 更新订单详情状态
     *          记录积分日志 -- 记录订单状态日志
     */
    public function confirm_receive_order(){
        $post = input('param.');
        $order = db('order')->where('id',$post['id'])->find();      //订单详情
        if(empty($order)){
            $this->error('找不到该订单信息',url('User/index'));
        }else if($order['order_status'] == 4){
            $this->error('该订单已收货，请勿重复操作',url('User/index'));
        }

        //更新订单支付状态
        $order_arr = [
            'order_status'=>4,
            'remark'=>'已收货',
            'confirm_time'=>time()
        ];
        db('order')->where('id',$post['id'])->update($order_arr);       //更新订单记录详情
        db('order_details')->where('order_id',$post['id'])->update(['status'=>4]);      //更新订单详情为确认收货状态


        $order_action = [
            'uid'=>$order['uid'],
            'order_id'=>$order['id'],
            'order_status'=>4,
            'pay_status'=>1,
            'status_desc'=>'已收货',
            'storeid'=>$order['store_id'],
            'addtime'=>time()
        ];
        db('order_action')->data($order_action)->insert();      //插入订单动作数据

//        $point_rule = db('sys_point')->where('id',2)->find();       //积分变更规则
//        $member = db('user')->where('uid',$order['uid'])->field('uid,level_point,pay_points,level_id')->find();
//        $level_point = ceil($order['final_amount']/$point_rule['point'])+$member['level_point'];        //当前的等级积分
//        $pay_points = ceil($order['final_amount']/$point_rule['point'])+$member['pay_points'];          //当前的权益积分
//        db('user')->where('uid',$member['uid'])->update(['level_point'=>$level_point,'pay_points'=>$pay_points]);       //更新会员当前的等级积分、权益积分
//
//        //积分记录数据
//        $point_log_arr = [
//            'uid'=>$order['uid'],
//            'store_id'=>$order['store_id'],
//            'order_id'=>$order['id'],
//            'uidtype'=>1,
//            'signid'=>2,
//            'type'=>1,
//            'point'=>ceil($order['final_amount']/$point_rule['point']),
//            'curpoint'=>$pay_points,
//            'type_cn'=>'订单完成,获得积分',
//            'remark'=>'订单完成获得积分',
//            'addtime'=>time(),
//        ];
//        db('user_point_log')->data($point_log_arr)->insert();       //新增记录数据
//        $rule = db('sys_level')->select();
//        $level_id = userLevel($rule,$level_point);
//        if($member['level_id'] != $level_id){
//            db('user')->where('uid',$order['uid'])->update(['level_id'=>$level_id]);        //更新会员的等级
//        }
//
//        //更新领取的优惠券状态 -- 置为可用状态
//        db('user_ycard')->where('receive_order_id',$post['id'])->update(['status'=>1]);

        $this->success('已确认收货',url('User/index'));
    }

    /**
     * @Author  lingyun
     * @Desc    重新支付订单
     *          重新修改订单号
     */
    public function create_repay_order(){
        $post = input('param.');
        $uid = session('_user_uid_.uid');
        $member = db('user')->where('uid',$uid)->field('uid,user_money,realname,level_id')->find();
        $order = db('order')->where('id',$post['id'])->field('id,uid,store_id,order_sn,final_amount,addtime,pay_status')->find();
        if($uid == ''){
            return ['code'=>0,'err_msg'=>'您目前还没有登陆，请先去登录','err_url'=>url('Login/loginin'),'err_button'=>'登录'];
        }
        if(empty($order)){
            return ['code'=>0,'err_msg'=>'找不到订单信息，无法发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
        }
        if($order['pay_status'] == 1){
            return ['code'=>0,'err_msg'=>'该订单已经支付，请勿重复支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
        }
        if($order['addtime']+172800<time()){
            db('order')->where('id',$post['id'])->update(['order_status'=>8]);
            db('order_details')->where('order_id',$post['id'])->update(['status'=>8]);
            $order_action = [
                'uid'=>$uid,
                'order_id'=>$order['id'],
                'action_user'=>0,
                'order_status'=>8,
                'pay_status'=>$order['pay_status'],
                'status_desc'=>'订单已关闭',
                'storeid'=>$order['store_id'],
                'addtime'=>time()
            ];
            db('order_action')->data($order_action)->insert();
            return ['code'=>0,'err_msg'=>'该订单已经关闭，如需购买请重新下单','err_url'=>url('User/index'),'err_button'=>'查看订单'];
        }

        $where_order_details = [
            'a.order_id'=>$order['id'],
        ];
        $join = [
            ['ys_store_goods_stock b','a.store_goods_stock_id=b.id','LEFT'],
            ['ys_goods_spec_detail c','a.spec_id=c.id','LEFT'],
            ['ys_goods d','a.goods_id=d.id','LEFT']
        ];
        $order_details = db('order_details')->alias('a')->join($join)->where($where_order_details)->field('a.*,a.spec_detail as spec_title,b.onsale,b.stock,b.is_deleted,c.price as goods_price,c.member_price,c.title,d.name,unit,d.logo,d.status,d.is_deleted as deleted,d.cat_id,d.member_level_id')->select();
        //重新创建订单号
        $order_sn = create_order_sn($order['uid']);

        $total_amount = 0;      //订单总价
        $delivery_fee = 0;      //计算运费
        $address_id = 0;        //默认地址id
        $num = count($order_details);               //购买商品数量
        $cate_id = '';               //商品分类
        foreach($order_details as $k=>$v){
            if($v['onsale'] == 0 || $v['is_deleted'] == 1 ){
                db('order')->where('id',$order['id'])->update(['order_status'=>8]);
                db('order_details')->where('order_id',$v['order_id'])->update(['status'=>8]);
                $order_action = [
                    'uid'=>$uid,
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>8,
                    'pay_status'=>$order['pay_status'],
                    'status_desc'=>'订单已关闭',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->data($order_action)->insert();
                return ['code'=>0,'err_msg'=>'您购买的商品已经下架，不能发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
                break;
            }

            if($v['goods_num'] > $v['stock']){
                db('order')->where('id',$order['id'])->update(['order_status'=>8]);
                db('order_details')->where('order_id',$v['order_id'])->update(['status'=>8]);
                $order_action = [
                    'uid'=>$uid,
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>8,
                    'pay_status'=>$order['pay_status'],
                    'status_desc'=>'订单已关闭',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->data($order_action)->insert();
                return ['code'=>0,'err_msg'=>'您购买的商品库存不足，不能发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
                break;
            }

            if($member['level_id'] != 1 && $member['level_id'] >= $v['member_level_id']){       //使用会员价
                $order_details[$k]['goods_price'] = $v['member_price'];
                $order_details[$k]['all_amount'] = $v['member_price']*$v['goods_num'];
                $total_amount += $order_details[$k]['all_amount'];
            }else{
                $order_details[$k]['all_amount'] = $v['goods_price']*$v['goods_num'];
                $total_amount += $order_details[$k]['all_amount'];
            }
            $cate_id .= ','.$v['cat_id'];
        }
        if(isMobile()){
            if(is_weixin()){
                $this->assign('is_mobile',0);
            }else{
                $this->assign('is_mobile',1);
            }
        }else{
            $this->assign('is_mobile',0);
        }

        $order_sn = create_order_sn($uid);      //订单编号
        db('order')->where('id',$order['id'])->update(['order_sn'=>$order_sn]);

        //默认收货地址,计算默认地址的运费
        $address = db('user_address')->where(['uid'=>$uid,'is_default'=>1])->find();
        if(!empty($address)){
            $result = $this->count_delivery_fee($address['address']);
            if($result['code'] == 0){
                $delivery_fee = 0;
                $address_id  = 0;
            }else{
                $delivery_fee = $result['msg'];
                $address_id = $address['id'];
            }
        }
        $sql = "SELECT id,name,logo,cat_id FROM ys_goods AS a WHERE 5> (SELECT COUNT(*) FROM ys_goods WHERE cat_id=a.cat_id AND id>a.id) AND a.is_online=1 ORDER BY a.id DESC";
        $tui_goods = Db::query($sql);
        $address_list = db('user_address')->where(['uid'=>$uid,'deleted'=>0])->order('id desc')->select();
        $final_amount = $delivery_fee+$total_amount;        //最终支付金额
        $city_list = db('city')->where(['status'=>1,'is_deleted'=>0])->select();
        $coupon = $this->get_coupon_list($final_amount,$cate_id);      //优惠券列表
        $cash_coupon = $this->get_cash_coupon($cate_id);
        $category = get_top_category();           //商品顶级分类
        $exp_category = get_exp_category();       //商品扩展分类

        $this->assign('order',$order);                      //订单信息
        $this->assign('tui_goods',$tui_goods);              //顶部推荐商品
        $this->assign('city',$city_list);                      //城市列表
        $this->assign('address',$address_list);              //默认收货地址
        $this->assign('default_address',$address);          //默认收货地址
        $this->assign('goods',$order_details);                  //商品
        $this->assign('num',$num);                      //购买数量
        $this->assign('total_amount',$total_amount);    //订单总价总价
        $this->assign('address_id',$address_id);        //默认收货地址
        $this->assign('delivery_fee',$delivery_fee);    //运费
        $this->assign('final_amount',$final_amount);    //最终金额
        $this->assign('member',$member);                //余额
        $this->assign('nowtime',date('Y-m-d',time()));
        $this->assign('order_sn',$order_sn);      //订单编号
        $this->assign('coupon',$coupon);                //优惠券
        $this->assign('count_coupon',count($coupon));                //优惠券
        $this->assign('cash_coupon',$cash_coupon);      //代金券
        $this->assign('count_cash_coupon',count($cash_coupon));      //代金券
        $this->assign('category',$category);      //代金券
        $this->assign('exp_category',$exp_category);      //代金券
        $this->assign('default_address',$address);      //默认收货地址
        return ['code'=>1];
    }

    /**
     * @Author  lingyun
     * @Desc    重新支付订单
     *          判断订单是否过期
     *          订单重新支付按照现在的支付价格进行计算
     *          订单的计算价格按照之前的项目
                 array(13) {
                    ["delivery_time_1"] => string(5) "00:00"
                    ["delivery_time_2"] => string(5) "23:59"
                    ["pay_type"] => string(1) "3"
                    ["user_note"] => string(64) "重新支付订单，会员重新支付订单！！！
                    "
                    ["id"] => string(1) "3"
                    ["address_id"] => string(2) "50"
                    ["coupon_id"] => string(2) "12"
                    ["cash_coupon_id"] => string(0) ""
                    ["shipping_price"] => string(5) "10.00"
                    ["total_amount"] => string(3) "378"
                    ["final_amount"] => string(3) "348"
                    ["coupon_price"] => string(2) "40"
                    ["cash_coupon_price"] => string(1) "0"
                 }
     */
    public function repay_order($post){
        $uid = session('_user_uid_.uid');
        //查询订单信息
        $order = db('order')->where('id',$post['order_id'])->find();
        //没有支付的订单
        if(empty($uid)){
            return ['code'=>0,'err_msg'=>'您目前没有登录，请重新登录','err_url'=>url('Login/loginin'),'err_button'=>'登录'];
        }
        $member = db('user')->where('uid',$uid)->find();
        if(empty($post['order_id']) || empty($order)){
            return ['code'=>0,'err_msg'=>'找不到订单信息，不能发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
        }

        if($order['pay_status'] == 1){
            return ['code'=>0,'err_msg'=>'该订单已经支付，请勿重复支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
        }

        //联表查询
        $join = [
            ['ys_goods b','a.goods_id=b.id','LEFT'],
            ['ys_goods_spec_detail c','a.spec_id=c.id','LEFT'],
            ['ys_store_goods_stock d','a.store_goods_stock_id=d.id','LEFT']
        ];
//        $order_details = db('order_details')->alias('a')->join('ys_goods_spec_detail b','a.spec_id=b.id','LEFT')->join('ys_store_goods_stock c','a.store_goods_stock_id=c.id','LEFT')->where('a.order_id',$post['order_id'])->join($join)->field('a.*,b.member_level_id,b.name,b.logo,b.member_level_id,c.title,c.price as goods_price,c.member_price,d.onsale,d.is_deleted,d.stock,b.peifang_ids,d.chengben,d.chengben_price')->select();

        $order_details = db('order_details')->alias('a')->where('a.order_id',$post['order_id'])->join($join)->field('a.*,b.member_level_id,b.name,b.logo,b.member_level_id,c.title,c.price as goods_price,c.member_price,d.onsale,d.is_deleted,d.stock,b.peifang_ids,d.chengben,d.chengben_price')->select();

        if(!empty($post['coupon_id'])){
            $coupon = db('user_ycard')->where('id',$post['coupon_id'])->find();
            if($coupon['user_start_time']<time() && $coupon['use_end_time']>time() && $coupon['is_used'] == 0){
                $coupon_price = $coupon['reduce'];
                $post['coupon_price'] = $coupon_price;
            }else{
                $post['coupon_id'] - 0;
                $coupon_price = 0;
                $post['coupon_price'] = 0;
            }
        }else{
            $coupon_price = 0;
            $post['coupon_id'] - 0;
            $post['coupon_price'] = 0;
        }

        if(!empty($post['cash_coupon_id'])){
            $cash_coupon = db('user_ycard')->where('id',$post['cash_coupon_id'])->find();
            if($cash_coupon['use_start_time']<time() && $cash_coupon['use_end_time']>time() && $cash_coupon['is_used'] == 0){
                $cash_coupon_price = $cash_coupon['value'];
                $post['cash_coupon_price'] = $cash_coupon_price;
            }else{
                $cash_coupon_price = 0;
                $post['cash_coupon_id'] = 0;
                $post['cash_coupon_price'] = 0;
            }
        }else{
            $cash_coupon_price = 0;
            $post['cash_coupon_id'] = 0;
            $post['cash_coupon_price'] = 0;
        }
//        $average_coupon = (float)$coupon['reduce']/$order['goods_num'];        //平均优惠券之后的价格
//        $average_cash_coupon = (float)$cash_coupon['value']/$order['goods_num'];    //平均代金券之后的价格

        $all_amount = 0;
        $final_amount = 0;
        $all_chengben = 0;
        $all_chengben_price = 0;

        //查询订单详情
        foreach($order_details as $k => $v){        //检查订单并且更新订单详情（更新价格价格）
            if($v['stock'] < $v['goods_num']){
                db('order')->where('id',$order['id'])->update(['order_status'=>8]);
                db('order_details')->where('order_id',$v['order_id'])->update(['status'=>8]);
                $order_action = [
                    'uid'=>$uid,
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>8,
                    'pay_status'=>$order['pay_status'],
                    'status_desc'=>'订单已关闭',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->data($order_action)->insert();
                return ['code'=>0,'err_msg'=>'您购买的商品库存不足，不能发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
                break;
            }
            if($v['onsale'] == 0 || $v['is_deleted'] == 1){
                db('order')->where('id',$order['id'])->update(['order_status'=>8]);
                db('order_details')->where('order_id',$v['order_id'])->update(['status'=>8]);
                $order_action = [
                    'uid'=>$uid,
                    'order_id'=>$order['id'],
                    'action_user'=>0,
                    'order_status'=>8,
                    'pay_status'=>$order['pay_status'],
                    'status_desc'=>'订单已关闭',
                    'storeid'=>$order['store_id'],
                    'addtime'=>time()
                ];
                db('order_action')->data($order_action)->insert();
                return ['code'=>0,'err_msg'=>'您购买的商品已下架，不能发起支付','err_url'=>url('User/index'),'err_button'=>'查看订单'];
                break;
            }

            //获取成本信息
            $chengben_result = $this->get_chengben($v['peifang_ids'],$v['chengben'],$v['chengben_price']);

            if($member['level_id'] >= $v['member_level_id']){       //会员价
                $order_details_data = [
                    'spec_detail'=>$v['title'],
                    'spec_price'=>$v['member_price'],
                    'discount_signal_price'=>$v['member_price']-($post['coupon_price']+$post['cash_coupon_price'])/$order['goods_num'],
                    'final_amount'=>($v['member_price']-($post['coupon_price']+$post['cash_coupon_price'])/$order['goods_num'])*$v['goods_num'],
                    'chengben'=>$chengben_result['chengben'],
                    'chengben_price'=>$chengben_result['chengben_price']
                ];
                db('order_details')->where('id',$v['id'])->update($order_details_data);
                $final_amount += $v['member_price']*$v['goods_num'];
                $all_amount += $v['member_price']*$v['goods_num'];
            }else{
                $order_details_data = [
                    'spec_detail'=>$v['title'],
                    'spec_price'=>$v['goods_price'],
                    'discount_signal_price'=>$v['goods_price']-($post['coupon_price']+$post['cash_coupon_price'])/$order['goods_num'],
                    'all_discount_prcie'=>$v['goods_price']-($post['coupon_price']+$post['cash_coupon_price'])/$order['goods_num'],
                    'final_amount'=>($v['goods_price']-($post['coupon_price']+$post['cash_coupon_price'])/$order['goods_num'])*$v['goods_num'],
                    'chengben'=>$chengben_result['chengben'],
                    'chengben_price'=>$chengben_result['chengbe_price']
                ];
                db('order_details')->where('id',$v['id'])->update($order_details_data);
                $final_amount += $v['goods_price']*$v['goods_num'];
                $all_amount += $v['goods_price']*$v['goods_num'];
            }

            $all_chengben = $v['goods_num']*$chengben_result['chengben'];
            $all_chengben_price = $v['goods_num']*$chengben_result['chengben_price'];
        }

        //我的收货地址
        $address = db('user_address')->where('id',$post['address_id'])->find();
        //计算邮费
        if($post['is_ziqu'] == 0){
            if(!empty($address)){
                $result = $this->count_delivery_fee($address['address']);
                if($result['code'] == 0){
                    return ['code'=>'0','error_msg'=>$result['msg'],'err_url'=>url('GoodsList/goods_detail',array('id'=>$param['goods_id'])),'err_button'=>'重新下单'];
                }else{
                    $shipping_price = $result['msg'];
                    $address_id = $address['id'];
                }
            }
        }else{
            $shipping_price = 0;
            $address_id = 0;
        }


        if($order['is_ziqu'] == 1){         //自取订单
            $final_amount = $final_amount-$coupon_price-$cash_coupon_price;
            $shipping_price=  0;
        }else{              //外卖订单
            $final_amount = $final_amount+$shipping_price-$coupon_price-$cash_coupon_price;
            $shipping_price = 0;
        }

//
//        if($param['is_ziqu'] == 1){         //自取订单
//            $final_amount = $final_amount-$shipping_price;
//            $shipping_price = 0;
//        }

        //订单更新数据
        $order_arr = [
            'consignee'=>$address['consignee'],
            'country'=>$address['country'],
            'province'=>$address['province'],
            'city'=>$address['city'],
            'district'=>$address['area'],
            'twon'=>$address['twon'],
            'address'=>$address['address'],
            'zipcode'=>$address['zipcode'],
            'mobile'=>$address['mobile'],
            'coupon_id'=>$post['coupon_id'],
            'coupon_price'=>$post['coupon_price'],
            'cash_coupon_id'=>$post['cash_coupon_id'],
            'cash_coupon_price'=>$post['cash_coupon_price'],
            'pay_type'=>$post['pay_type'],
            'address_id'=>$address['id'],
            'order_sn'=>$order['order_sn'],
            'shipping_price'=>$shipping_price,
            'goods_price'=>$all_amount,
            'final_amount'=>$final_amount,
            'order_amount'=>$final_amount,
            'delivery_time'=>'',   //配送时间
            'user_note'=>$post['user_note'],
            'chengben'=>$all_chengben,
            'chengben_price'=>$all_chengben_price,
            'is_ziqu'=>$post['is_ziqu'],
            'pay_type_two'=>0
        ];
        //更新订单数据
        db('order')->where('id',$post['order_id'])->update($order_arr);

        //可以领取的优惠券列表 -- srart   移到此处防止会员直接访问链接多次领取
        $time = time();
        $sql = "select a.*,ifnull(b.coupon_id,0) as is_received from ys_store_coupon as a left join (select coupon_id,store_id,uid from ys_user_ycard where uid=".$uid." and store_id=".cookie('store_id').") as b on a.id=b.coupon_id where a.store_id=".cookie('store_id')." and a.condition<=".$final_amount." and a.send_start_time<".$time." and a.send_end_time>".$time." and a.is_deleted=0 and a.type=0 and a.status=1 and a.create_num>a.send_num";
        $receive_coupon = Db::query($sql);
        $total = count($receive_coupon);
        $receive_coupon_id = '';         //可以领取的优惠券id
        foreach($receive_coupon as $k => $v){
            if($v['is_received'] == 0){
                $receive_coupon_id .= $v['id'].",";
            }
        }
        db('order')->where('order_sn',$order['order_sn'])->update(['receive_coupon_id'=>$receive_coupon_id]);        //更新可以领取的优惠券id
        //可以领取的优惠券列表 -- end   移到此处防止会员直接访问链接多次领取


        return ['code'=>1,'order_sn'=>$order['order_sn']];
    }


    /**
     * @Author  lingyun
     * @Desc    计算商品成本
     * @param $peifang_ids  配方id
     * @param $chengben 成本
     * @param $chengben_price   成本价
     * @return array
     */
    private function get_chengben($peifang_ids,$chengben,$chengben_price){
        if(empty($chengben) || empty($chengben_price)){         //没有成本价
            if(empty($peifang_ids)){
                $chengben = 0;
                $chegnben_price = 0;
            }
            $peifang = db('goods_peifang')->where('id','in',$peifang_ids)->field('chengben,chengben_price')->select();

            $chengben = array_sum(array_map(function($peifang){return $peifang['chengben'];}, $peifang));
            $chengben_price = array_sum(array_map(function($peifang){return $peifang['chengben_price'];}, $peifang));
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }else{
            return ['chengben'=>$chengben,'chengben_price'=>$chengben_price];
        }

    }


    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @Param   $address    收货地址
     */
    public function count_delivery_fee($address=''){
        $root = request()->domain();
        $config_arr = config('dada');
        $config_arr['url'] = "http://newopen.imdada.cn/api/order/queryDeliverFee";          //订单详情查询
        $dada_obj = new DadaOpenapi($config_arr);
        $data_arr['origin_id'] = build_order_no().cookie('store_id');
        $store = db('store')->alias('a')->join('ys_city b','a.city_code=b.code','LEFT')->where('a.id',cookie('store_id'))->field('a.*,b.dada_code')->find();            //门店信息
        $data_arr['shop_no'] = $store['dada'];           //门店编号
        $data_arr['city_code'] = $store['dada_code'];           //门店编号
        $data_arr['cargo_price'] = 0.01;           //订单金额
        $data_arr['is_prepay'] = 0;           //是否需要垫付，0否
        $data_arr['receiver_name'] = '一朵';           //是否需要垫付，0否
        $data_arr['receiver_address'] = $address;           //收货地址
        $data_arr['callback'] = $root.'/index.php/index/dada/count_delivery_fee';           //是否需要垫付，0否
        $data_arr['receiver_phone'] = '18757685769';           //是否需要垫付，0否
        $fee_info = $dada_obj->pre_count_delevety_fee($data_arr);          //与计算订单运费
        $result = json_decode($fee_info,true);
        if(empty($result)){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
        }else if($result['status'] =='fail' && $result['code'] != 0){
            return ['code'>0,'msg'=>'地址填写错误或不在配送范围，请检查并核实'];
//           $this->error('地址填写错误或不在配送范围，请检查并核实','');
        }

        $price = $this->getDeliveryFee($result['result']['distance']);

        return ['code'=>1,'msg'=>$price['msg']];

    }

    /**
     * @Author  lingyun
     * @Desc    计算运费
     * @param $distance
     * @return array
     */
    private function getDeliveryFee($distance){
        $distance = $distance/2/500;
        //查询运费信息
        $data = Db::name('delivery_fee')->where('is_deleted',0)->order('distance asc')->select();
        foreach($data as $k => $v){
            if($distance < $v['distance']){
                return ['code'=>1,'msg'=>$v['price']];
                break;
            }
        }
        $val = end($data);
        return ['code'=>1,'msg'=>$val['price']];
    }

    /**
     * @Author  lingyun
     * @Desc    余额付款
     * @param $order_sn   订单编号
     * @param $final_amount     最终支付金额
     */
    public function pay_by_credit($order_sn,$final_amount){
        $uid = session('_user_uid_.uid');
        $member = db('user')->where('uid',$uid)->field('uid,user_money,realname,openid')->find();
        if($member['user_money'] < $final_amount){
            $this->error('会员余额不足，请及时充值','');
        }


        $order = db('order')->where('order_sn',$order_sn)->field('id,coupon_id,cash_coupon_id,store_id,uid,order_sn')->find();

        //构造余额支付记录数据
        $data_arr = [
            'uid'=>$uid,
            'admin_id'=>0,
            'store_id'=>$order['store_id'],
            'order_id'=>$order['id'],
            'order_sn'=>$order['order_sn'],
            'pay_time'=>time(),
            'pay_status'=>1,
            'pay_type'=>3,
            'amount'=>$final_amount,
            'cur_amount'=>$member['user_money']-$final_amount,
            'sign'=>2,
            'chargetype'=>1,
            'charge_cn'=>'支付订单',
            'addtime'=>time()
        ];
        //记录余额记录
        db('user_wallet_log')->data($data_arr)->insert();       //记录余额记录

        $pay_log_arr = [
            'order_id'=>$order['id'],
            'order_sn'=>$order['order_sn'],
            'uid'=>$uid,
            'pay_type'=>3,
            'pay_sign'=>1,
            'amount'=>$final_amount,
            'remark'=>'支付订单',
            'addtime'=>time()
        ];
        db('pay_log')->data($pay_log_arr)->insert();            //记录支付记录

        $cur_amount = $member['user_money'] - $final_amount;    //会员当前的余额
        db('user')->where('uid',$uid)->update(['user_money'=>$cur_amount]);     //更新会员当前的余额
//        halt($res);
        db('order')->where('order_sn',$order_sn)->update(['pay_status'=>1,'pay_time'=>time(),'order_status'=>1,'remark'=>'已支付']);      //更新订单支付状态

        db('order_details')->where('order_id',$order['id'])->update(['status'=>1]);     //更新订单详情的支付状态

        //更新优惠券的使用情况
        db('user_ycard')->where('id',$order['coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);
        db('user_ycard')->where('id',$order['cash_coupon_id'])->update(['order_id'=>$order['id'],'used_time'=>time(),'is_used'=>1]);


        //更新门店库存
        $order_details = db('order_details')->where('order_id',$order['id'])->select();
        foreach($order_details as $k => $v){
            db('store_goods_stock')->where('id',$v['store_goods_stock_id'])->setDec('stock',$v['goods_num']);
        }

        //订单动作数据
        $data_action = [
            'uid'=>$uid,
            'order_id'=>$order['id'],
            'action_user'=>0,
            'order_status'=>1,
            'pay_status'=>1,
            'status_desc'=>'已支付，待发货',
            'storeid'=>$order['store_id'],
            'addtime'=>time()
        ];
        db('order_action')->data($data_action)->insert();       //新增订单数据

        //存在会员的openid就推送模板消息
        if(!empty($member['openid'])){
            //推送模板消息
            $array = [
                "type"   	  =>1,
                "touser" 	  =>$member["openid"],
                "template_id"=>config("mobanid.xiadan")["tempid"],
                "url" 		  =>config("mobanid.xiadan")["url"],
                "topcolor"  =>"#743A3A",
                "data"   =>[
                    "first" 	    =>["value"=>"支付成功",        		"color"=>"#743A3A"],
                    "keyword1"		=>["value"=>$order['order_sn'], 		"color"=>"#743A3A"],
                    "keyword2"		=>["value"=>$final_amount, 		"color"=>"#743A3A"],
                    "keyword3"		=>["value"=>"微信支付","color"=>"#743A3A"],
                    "remark"		=>["value"=>"感谢您的购买，请注意查收商品", 			"color"=>"#743A3A"],
                ]
            ];
            $wein = new WeixinService();
            $rest  = $wein->sendmsg($array);
        }
        //支付成功，跳转至领取优惠券页面
        $this->success('支付成功',url('PayComplete/get_coupon')."?out_trade_no=".$order_sn,3);
    }

    /**
     * @Author  lingyun
     * @Desc    订单商品评价  上传base64图片  3张
     * 2018-05-03
     */
    public function comment_order_goods(){
        $post = input('post.');

        $images = '';
        $accessKey = config('qiniu.accesskey');//七牛云accesskey
        $secretKey = config('qiniu.secretkey');//七牛云secretkey
        $bucket = config('qiniu.bucket');//七牛云存储空间
        $url = config('qiniu.backurl');//七牛云绑定的域名默认为测试域名
        $qiniu = new Qiniu($accessKey,$secretKey,$bucket);

        if(!empty($post['image_1'])){           //
            preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($post['image_1']), $result1);
//            halt($result);
//            $base64 = str_replace('data:image/png;base64,', '', trim($post['image_1']));
            $base64 = str_replace($result1[1], '', trim($post['image_1']));
            $ret = $qiniu->baseUplod($base64,$bucket);
            if($ret){
                $images .= $url.'/'.$ret."|";
            }
        }

        if(!empty($post['image_2'])){           //
            preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($post['image_2']), $result2);
            $base64 = str_replace($result2[1], '', trim($post['image_2']));
            $ret = $qiniu->baseUplod($base64);
            if ($ret) {
                $images .= $url.'/'.$ret."|";
            }
        }

        if(!empty($post['image_3'])){           //
            preg_match('/^(data:\s*image\/(\w+);base64,)/', trim($post['image_3']), $result3);
            $base64 = str_replace($result3[1], '', trim($post['image_3']));
            $ret = $qiniu->baseUplod($base64);
            if ($ret) {
                $images .= $url.'/'.$ret."|";
            }
        }
        //七牛云配置
//        $qiniu = config('qiniu');
//        $name=time().session('_user_uid_.uid').$_FILES['images']['name'];             //文件名称
//        $filePath=$_FILES['images']['tmp_name'];     //文件路径
//        $type=$_FILES['images']['type'];             //文件类型
//
//        $upManager = new UploadManager();
//        $auth = new Auth($qiniu['accesskey'], $qiniu['secretkey']);
//        $token = $auth->uploadToken($qiniu['bucket']);
//        list($ret, $error) = $upManager->putFile($token,$name,$filePath,null,$type,false);
//        if(!empty($error)){
//            $this->error('图片上传失败,请稍后再试！',url('User/index'));
//        }
//
//        $post['is_anonymous'] = !empty($post['is_anonymous'])?1:0;
        //订单详情
        $order = db('order_details')->where('id',$post['id'])->find();

        $data = [
            'goods_id'=>$order['goods_id'],
            'content'=>$post['pingjia'],
            'is_show'=>0,
            'uid'=>session('_user_uid_.uid'),
            'images'=>trim($images,'|'),
            'order_id'=>$order['order_id'],
            'is_deleted'=>0,
            'is_anonymous'=>0,
            'store_id'=>$order['storeid'],
            'addtime'=>time()
        ];

        $res = db('goods_comment')->data($data)->insert();
        if($res>0){
             db('order_details')->where('id',$post['id'])->update(['is_comment'=>1]);       //更新评价
            $order_details = db('order_details')->where('order_id',$order['order_id'])->column('is_comment');
            $is_comment = 1;
            foreach($order_details as $k => $v){
                if($v == 0){
                    $is_comment = 0;
                }
            }
            db('order')->where('id',$order['order_id'])->update(['is_comment'=>$is_comment]);
             $this->success('评价成功','');
        }else{
             $this->error('评价失败','');
        }

    }

    /**
     * @Author  lingyun
     * @Desc    我的邀请二维码
     */
    public function pay_qrade(){
        $pay_code = $this->userinfo['pay_code'];
        $qrCode=new QrCode();
        $url ='http://www.baidu.com'.$pay_code;
        $qrCode->setText($url)
            ->setSize(300)
            ->setLabelFontPath(VENDOR_PATH.'endroid\qrcode\assets\noto_sans.otf')
            //->setErrorCorrectionLevel('high')
            ->setForegroundColor(array('r' => 0, 'g' => 0, 'b' => 0, 'a' => 0))
            ->setBackgroundColor(array('r' => 255, 'g' => 255, 'b' => 255, 'a' => 0))
            ->setLabelFontSize(16);
        header('Content-Type: '.$qrCode->getContentType());
        echo $qrCode->writeString();
        exit;
    }

    /**
     * @Author  lingyun
     * @Desc    优惠券列表
     * @param $total_amount
     * @param $cate_id
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function get_coupon_list($total_amount,$cate_id){
        $request = request();
        $uid = session('_user_uid_.uid');        //会员id
        $store_id = cookie('store_id');         //门店id
        $post = input('param.');                 //代金券金额

        //商品优惠券，1关注券 ， 2现金券
        $time = time();         //当前的时间
        $where_coupon_0 = [
            'a.store_id'=>$store_id,
            'a.uid'=>$uid,
            'a.is_used'=>0,
            'a.type'=>['neq','2'],
            'a.morethan'=>['elt',$total_amount],
            'a.use_start_time'=>['lt',$time],
            'a.use_end_time'=>['gt',$time],
            'a.cat_id'=>['in','0,'.$cate_id],     //优惠券的类型
            'a.status'=>1
        ];
        //普通优惠券 -- 关注券列表
        $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->field('a.*,b.img')->where($where_coupon_0)->select();
        return $coupon;

    }

    /**
     * @Author  lingyun
     * @Desc    根据订单的金额获取会员的代金券
     * @Param   $cate_id 商品分类
     */
    public function get_cash_coupon($cate_id){
        $uid = session('_user_uid_.uid');        //会员id
        $store_id = session('store_id');        //门店id
        $post = input('param.');
        $time = time();         //当前时间
        $where = [
            'a.uid'=>$uid,
            'a.store_id'=>$store_id,
            'a.is_used'=>0,
            'a.type'=>2,
            'a.cat_id'=>['in','0,'.$cate_id],
            'a.status'=>1,
            'a.use_start_time'=>['lt',$time],
            'a.use_end_time'=>['gt',$time],
        ];
        //代金券列表
        $coupon = db('user_ycard')->alias('a')->join('ys_store_coupon b','a.coupon_id=b.id','LEFT')->where($where)->field('a.*,b.img')->select();
        return $coupon;
    }

}